<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>软件下载器</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">

    <link rel="stylesheet" href="/static/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/css/base.css" media="all">
</head>
<body class="layui-layout-body">
<div class="layui-layout layui-layout-admin">
    <div class="layui-header">
        <div class="layui-logo"><h1>软件下载器</h1></div>
        <!-- 头部区域（可配合layui已有的水平导航） -->
        <ul class="layui-nav layui-layout-right">
            <li class="layui-nav-item">
                <a href="javascript:;">
                    {{.username}}
                </a>
                <dl class="layui-nav-child">
                    <dd><a href="">基本资料</a></dd>
                    <dd><a href="">安全设置</a></dd>
                </dl>
            </li>
            <li class="layui-nav-item"><a href="/exit">安全退出</a></li>
        </ul>
    </div>

    <div class="layui-side layui-bg-black">
        <div class="layui-side-scroll">
            <!-- 左侧导航区域（可配合layui已有的垂直导航） -->
            <ul class="layui-nav layui-nav-tree" lay-filter="test">
                <li class="layui-nav-item"><a href="/">下载管理</a></li>
                <li class="layui-nav-item"><a href="/public" target="_blank">文件管理</a></li>
            </ul>
        </div>
    </div>

    <div class="layui-body">
        <!-- 内容主体区域 -->
        <div style="padding: 15px;">
            <div class="layui-row">
                <div class="layui-col-xs6">
                    <button type="button" class="layui-btn layui-btn-warm" data-method="addTaskBtn">新增下载任务</button>
                </div>
                {{/*                <div class="layui-col-xs6">*/}}
                {{/*                    <button type="button" class="layui-btn layui-btn-warm" data-method="sendMsgBtn">发送信息</button>*/}}
                {{/*                </div>*/}}
            </div>
            <table class="layui-hide" id="taskListTable" lay-filter="tableEvent"></table>
        </div>
    </div>

    <div class="layui-footer">
        © Simon 软件下载器
    </div>
</div>
<script type="text/html" id="toolBar">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script src="/static/layui/layui.js" charset="utf-8"></script>
<script>
    //JavaScript代码区域
    layui.use(['element', 'table', 'layer'], function () {
        var $ = layui.jquery,
            layer = layui.layer,
            table = layui.table;
        var timerFlag = false,
            timer,
            dataInfo = [];

        table.on('tool(tableEvent)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data; //获得当前行数据
            var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
            if (layEvent === 'del') { //删除
                layer.confirm('真的删除行么', function (index) {
                    obj.del();
                    layer.close(index);
                    $.get("/taskDel/" + data.Id, function (res, status) {
                        console.log(res)
                    });
                });
            }
        });

        table.render({
            id: "tableId",
            elem: '#taskListTable',
            limit: 26,
            cols: [[
                {field: 'Id', title: 'ID', width: 56},
                {field: 'Url', title: '下载地址'},
                {field: 'Name', title: '文件名', width: 180},
                {field: 'Progress', title: '下载进度', width: 180},
                {field: 'Status', title: '状态', width: 60},
                {title: '操作', toolbar: '#toolBar', width: 130},
            ]],
            data: dataInfo
        });

        $.get('/taskList', function (res, status) {
            dataInfo = res.data
            $.each(dataInfo, function (n, item) {
                item.Progress = "0%";
                if (item.Status == '30') {
                    item.Progress = "100%";
                }
            })
            table.reload("tableId", {data: dataInfo})
        })

        //建立WebSocket通讯
        var socket = new WebSocket('ws://{{.hostname}}:3000/getDownloadProcss');
        //连接成功时触发
        socket.onopen = function () {
            console.log("onopen:", "连接服务器成功!!!")
        };
        //监听收到的消息
        socket.onmessage = function (res) {
            if (!timerFlag) {
                console.log("设置定时器")
                timer = setInterval(function () {
                    table.reload("tableId", {data: dataInfo})
                }, 600);
            }
            timerFlag = true
            msgInfo = $.parseJSON(res.data)
            $.each(dataInfo, function (n, item) {
                if (item.Id == msgInfo.msg.id) {
                    if (!msgInfo.msg.finish) {
                        calc = (msgInfo.msg.cost / msgInfo.msg.total * 100).toFixed(1);
                        item.Progress = calc + "%";
                    } else {
                        item.Progress = "100%";
                        clearInterval(timer)
                        timerFlag = false
                        table.reload("tableId", {data: dataInfo})
                    }
                }
                console.log("progress " + item.Id + ":" + item.Progress);
            })
        };

        var active = {
            addTaskBtn: function () {
                layer.open({
                    type: 2,
                    title: '添加下载任务',
                    shadeClose: true,
                    shade: 0.8,
                    area: ['600px', '260px'],
                    content: '/showAddTaskPanel'
                });

            },
            sendMsgBtn: function () {
                //更多情况下，一般是传递一个对象
                $.get("/Test", function (res, status) {
                    console.log(res)
                });
                // socket.send(JSON.stringify({
                //     emit: 'btnEvent',
                //     data: {"name":"simon"}
                // }));
            }
        };

        $('.layui-btn').on('click', function () {
            var othis = $(this), method = othis.data('method');
            active[method] ? active[method].call(this, othis) : '';
        });
    });
</script>
</body>
</html>
